<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item v-for="pathTitle in pathTitles" :key="pathTitle">{{pathTitle}}</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="box-card">

            <div class="header-search-add">
                <div class="input-search">
                    <el-input placeholder="请输入用户名" v-model="query">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
                    </el-input>
                </div>
                <el-button type="primary" class="add-user-btn" @click="addUserDialogVisible = true">添加用户</el-button>
            </div>
            <el-table
              :data="users"
              >
                <el-table-column
                  label="#"
                  type="index"
                  >
                </el-table-column>
                <el-table-column
                  label="姓名"
                  prop="username"
                >
                </el-table-column>
                <el-table-column
                  prop="user_email"
                  label="邮箱"
                >
                </el-table-column>
                <el-table-column
                  prop="user_tel"
                  label="电话"
                >
                </el-table-column>
                <el-table-column
                  prop="user_xueli"
                  label="学历"
                >
                </el-table-column>
                <el-table-column
                  label="状态"
                >
                  <template slot-scope="{row}">

                      <el-switch v-model="row.is_active" @change="activeChange(row)">
                      </el-switch>
                  </template>
                </el-table-column>
                <el-table-column
                  label=操作
                  width="180"
                >
                    <template slot-scope="{row}">
                        <div>
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditor(row)"></el-button>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(row)"></el-button>
                            <el-tooltip class="item" effect="dark" content="设置权限" placement="top" :enterable="false">
                                <el-button type="warning" icon="el-icon-s-tools" size="mini"></el-button>
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="page"
              :page-size="pageSize"
              :total="total"
              :page-sizes="[2, 5, 10]"
              layout="total,sizes, prev, pager, next"
            >
            </el-pagination>
       </el-card>
        <el-dialog

                title="添加用户"
                :visible.sync="addUserDialogVisible"
                width="680px"
                :before-close="dialogBeforeClose"
        >
            <el-form ref="userDialogForm" :model="userData" :rules="userRules">
                <el-form-item label-width="80px" label="用户名" prop="username">
                    <el-input placeholder="用户" v-model="userData.username">
                    </el-input>
                </el-form-item>
                <el-form-item label-width="80px" label="邮箱" prop="email">
                    <el-input placeholder="邮箱" v-model="userData.email">
                    </el-input>
                </el-form-item>
                <el-form-item label-width="80px" label="密码" prop="password">
                    <el-input placeholder="密码" show-password v-model="userData.password">
                    </el-input>
                </el-form-item>
                <el-form-item label-width="80px" label="手机号" prop="phone">
                    <el-input placeholder="手机号" v-model="userData.phone">
                    </el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addUserDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">{{this.userData.user_id ===''?'添加用户':'修改用户'}}</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>

  import getPathTitleMixin from "mixin/getPathTitleMixin";

  import {userList,addUser,changeActive,updateUser,deleteUser} from "network/userRequest/UserRequest";
  import {checkEmail,checkPhone} from "common/utils";


  export default {
    name: "UserList",
    mixins:[getPathTitleMixin],
    data:function(){


        return {
            addUserDialogVisible:false,
            query:'',
            page:1,
            pageSize:5,
            lastPage:0,
            total:0,
            users:[],
            userData:{
              username:'',
              password:'',
              email:'',
              phone:'',
              user_id:''
            },
            userRules:{
              username:[
                {required:true,message:"请输入用户名",trigger:'blur'},
                {min:3,message:'用户名至少3个字符', trigger:'blur'}
              ],
              email:[
                {required:true,message:"请输入邮箱",trigger:'blur'},
                {validator:function (rule,email,callback) {

                    if (!checkEmail(email)){
                     callback(new Error('邮箱格式错误'));
                  }
                  callback();
                },trigger:'blur'}
              ],
              password:[
                {required:true,message:"请输入密码",trigger:'blur'},
                {min:6,message: '密码至少6位',trigger: 'blur'}
              ],
              phone:[
                {required:true,message:"请输入手机号",trigger:'blur'},
                {validator:function (rule,phone,callback) {

                    if (!checkPhone(phone)){
                      callback(new Error('手机号格式错误'));
                    }
                    callback();
                  },trigger:'blur'}
              ]
            }
        }
    },
    created:function(){

        //获取用户列表
        this.getUserList();
    },
    computed:{

        userState(){
            return true;
        },
    },
    watch:{
      addUserDialogVisible(newValue){

        if (!newValue){
          let form = this.$refs['userDialogForm'];
          if (form){
            form.resetFields();
            this.userData.user_id = '';
          }
        }
      }
    },
    methods:{

        getUserList(){

            userList({

                query: this.query,
                page: this.page,
                pageSize:  this.pageSize
            }).then(data=>{

                this.total = data.total;
                this.lastPage = data.lastPage;
                this.users = data.users;
            });
        },

        handleSizeChange(value){

            console.log(value);
            this.pageSize = value;
            this.getUserList();
        },
        handleCurrentChange(page){

            this.page = page;
            this.getUserList();
        },
        dialogBeforeClose(done){

          done();
        },
        addUser(){

          this.$refs['userDialogForm'].validate(data=>{

            if (data !== true){

              return;
            }
            if (this.userData.user_id !== ''){

                this.updateUser();
            }else {

              this.addUser();
            }

          });

        },
        activeChange(row){

          console.log(row);

          changeActive({
                'userId': row.user_id,
                'active':row.is_active?1:2
          }).then(data=>{

            this.getUserList();
          }).catch(error=>{
            row.is_active = !row.is_active;
          });

        },
      showEditor(row){

        this.userData.phone = row.user_tel;
        this.userData.user_id = row.user_id;
        this.userData.username = row.username;
        this.userData.email = row.user_email;
        this.addUserDialogVisible = true;
      },
      addUser(){
        addUser({
          'username':this.userData.username,
          'user_email':this.userData.email,
          'password':this.userData.password,
          'user_tel':this.userData.phone
        }).then(data=>{

          this.addUserDialogVisible = false;
          this.getUserList();
        });
      },
      updateUser(){

          updateUser({
            'user_id':this.userData.user_id,
            'username':this.userData.username,
            'user_email':this.userData.email,
            'password':this.userData.password,
            'user_tel':this.userData.phone
          }).then(data=>{

            this.addUserDialogVisible = false;
            this.getUserList();
          });
      },
      deleteUser(row){

        this.$messageBox(`删除 ${row.username}用户`, '删除用户', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          showCancelButton:true,
          type: 'warning'
        }).then(() => {

           deleteUser({
             userId:row.user_id
           }).then(data=>{

             this.getUserList();
           });

        }).catch(() => {


        });

      }
    }
  }
</script>

<style lang="less" scoped>

    .el-breadcrumb{
        margin-bottom: 20px;
    }

    .header-search-add{

        margin-top: 10px;
        display: flex;
        .add-user-btn{
            margin-left: 40px;
        }
    }

    .input-search{
        width: 400px;
        color:#ff4949;
    }

    .el-table{

        margin-top: 30px;
    }

    .el-pagination{
        margin-top: 20px;
    }

</style>
